package com.hatom.cameraxhelp.fragment.dialog;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Outline;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.media.FaceDetector;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.internal.utils.ImageUtil;
import androidx.camera.view.PreviewView;
import androidx.fragment.app.DialogFragment;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hatom.cameraxhelp.R;
import com.hatom.cameraxhelp.bean.CameraParam;
import com.hatom.cameraxhelp.utils.Base64Utils;
import com.hatom.cameraxhelp.utils.CameraXHelp;
import com.hatom.cameraxhelp.widgets.CircleProgressView;
import com.hatom.cameraxhelp.widgets.MultFaceBorderView;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class FaceChooseDialog extends DialogFragment {

    private PreviewView camera_preview;

    private CameraXHelp cameraXHelp;//CrameX工具类
    private MultFaceBorderView faceShowView;//识别框
    private CircleProgressView circleProgressView;//外扩圆罩

    private GetFace getFace;



    private CameraParam mCameraParam;

    public FaceChooseDialog(CameraParam cameraParam) {
        this.mCameraParam=cameraParam;
    }

    public FaceChooseDialog() {
        this.mCameraParam=new CameraParam();//初始化
    }

    public void setGetFace(GetFace getFace) {
        this.getFace = getFace;
    }

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    }


    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.camerax_fragment_dialogface_camera, container, false);
        initView(view);
        return view;
    }

    private void initWindow() {
        Window window = requireDialog().getWindow();

        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);
        WindowManager.LayoutParams layoutParams = window.getAttributes();//获取dialog布局的参数
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;//全屏
        layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;//全屏
        //设置导航栏颜
        window.setNavigationBarColor(Color.TRANSPARENT);
        //内容扩展到导航栏
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        if (Build.VERSION.SDK_INT >= 28) {
            layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
        }

        layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
        layoutParams.windowAnimations = android.R.anim.fade_in;
        window.requestFeature(Window.FEATURE_NO_TITLE);

        window.setAttributes(layoutParams);
    }

    private void initView(View view) {
        initWindow();
        camera_preview = view.findViewById(R.id.dialogface_camera_preview);
        FrameLayout frameLayout = view.findViewById(R.id.frameLayout);
        faceShowView = view.findViewById(R.id.faceshow);

        circleProgressView = view.findViewById(R.id.circle);


        //圆形剪裁
        camera_preview.setImplementationMode(PreviewView.ImplementationMode.COMPATIBLE);
        ViewOutlineProvider outline=new ViewOutlineProvider() {
            @Override
            public void getOutline(View view, Outline outline) {
                outline.setRoundRect(new Rect(0, 0, view.getWidth(),view.getHeight()), view.getWidth()/2);
            }
        };
        camera_preview.setOutlineProvider(outline);
        camera_preview.setClipToOutline(true);


        circleProgressView.setProgressStartColor(mCameraParam.getProgressStartColor());
        circleProgressView.setProgressEndColor(mCameraParam.getProgressEndColor());
        faceShowView.setMaxStayTime(mCameraParam.getMaxStayTime());

        AppCompatImageView close_dialog = view.findViewById(R.id.close_dialog);
        close_dialog.setColorFilter(Color.BLACK);
        close_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getFace != null) {
                    getFace.error("close");
                }
                dismiss();
            }
        });//关闭按钮
        AppCompatImageView translate_dialog = view.findViewById(R.id.translate_dialog);
        translate_dialog.setColorFilter(Color.BLACK);
        translate_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cameraXHelp!=null){
                    cameraXHelp.transCamera();
                }
            }
        });//翻转按钮
        frameLayout.post(new Runnable() {
            @Override
            public void run() {
                circleProgressView.setPaintWidth((float) frameLayout.getWidth() / 3);
                circleProgressView.setCenterPoint(frameLayout.getX() + (float) frameLayout.getWidth() / 2, frameLayout.getY() + (float) frameLayout.getHeight() / 2);
            }
        });//等待加载好 初始化圆位置

        XXPermissions.with(requireActivity())
                .permission(Permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all){
                            initCamera();
                        }else {
                            ToastUtils.showShort("相机权限未通过");
                        }
                    }
                });

    }

    //初始化相机
    private void initCamera(){
        cameraXHelp = new CameraXHelp();//初始化工具类对象
        cameraXHelp.setBackCamera(mCameraParam.isBlackCamera());
        faceShowView.setGetMultFace(new MultFaceBorderView.GetMultFace() {
            @Override
            public void stayface(@Nullable @org.jetbrains.annotations.Nullable ArrayList<Bitmap> bitmaps) {
                if (bitmaps == null || bitmaps.size() == 0) {
                    return;
                }
                if (getFace != null) {
                    getFace.getPhoto(Base64Utils.bitmapToBase64(bitmaps.get(0)));
                    dismiss();
                }
            }

            @Override
            public void getprogress(int progress) {
                circleProgressView.setProgress(progress);
            }
        });

        cameraXHelp.setUpCamera(FaceChooseDialog.this, requireActivity(), camera_preview.getSurfaceProvider(), new CameraXHelp.AnalaysListener() {
            @SuppressLint("RestrictedApi")
            @Override
            public void analyze(@NonNull @NotNull ImageProxy imageProxy) {
                Bitmap rgbBitmap = null;
                try {
                    rgbBitmap = ImageUtils.getBitmap(Objects.requireNonNull(ImageUtil.yuvImageToJpegByteArray(imageProxy, new Rect(0, 0, imageProxy.getWidth(), imageProxy.getHeight()), 80)), 0)
                            .copy(Bitmap.Config.RGB_565, true);
                } catch (ImageUtil.CodecFailedException e) {
                    e.printStackTrace();
                }
                // 获取数据旋转角
                int rotate = imageProxy.getImageInfo().getRotationDegrees();
                Bitmap bitmap;
                if (rgbBitmap==null){
                    return;
                }
                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    rotate = rotate + 90;

                    Matrix matrix = new Matrix();
                    matrix.setRotate(rotate, 0, 0);
                    float[] values = {-1f, 0.0f, 0.0f, 0.0f, 1f, 0.0f, 0.0f, 0.0f, 1.0f};
                    matrix.setValues(values);
                    bitmap = Bitmap.createBitmap(rgbBitmap, 0, 0, rgbBitmap.getWidth(), rgbBitmap.getHeight(), matrix, true);
                } else {
                    if (!cameraXHelp.isBackCamera()){
                        Matrix matrix = new Matrix();
                        float[] values = {-1f,0.0f,0.0f,0.0f,1f,0.0f,0.0f,0.0f,1.0f};
                        matrix.setValues(values);
                        matrix.preRotate(rotate);//矩阵前乘
                        bitmap = Bitmap.createBitmap(rgbBitmap, 0, 0, rgbBitmap.getWidth(), rgbBitmap.getHeight(), matrix, true);

                    }else {
                        bitmap = ImageUtils.rotate(rgbBitmap, rotate, 0, 0);
                    }
                }

                assert bitmap != null;
                float scaleX = (float) camera_preview.getWidth() / bitmap.getWidth();
                float scaleY = (float) camera_preview.getHeight() / bitmap.getHeight();
                FaceDetector detector = new FaceDetector(bitmap.getWidth(), bitmap.getHeight(), 1);
                FaceDetector.Face[] faces = new FaceDetector.Face[1];
                int number = detector.findFaces(bitmap, faces);

                if (number > 0) {
                    faceShowView.updateFaces(faces, scaleX, scaleY, number, bitmap);
                } else {
                    faceShowView.removeRect();
                }
            }

            @Override
            public void error(String error) {
                if (getFace != null) {
                    getFace.error(error);
                }
            }
        });
    }



    @Override
    public void onDismiss(@NonNull @NotNull DialogInterface dialog) {
        super.onDismiss(dialog);
        if (getFace != null) {
            getFace.error("onDismiss");
        }
    }

    public interface GetFace {
        void getPhoto(String base64);

        void error(String msg);
    }
}
